package com.atguigu.juc.day03.scene;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class Demo03Semaphore {

    public static void main(String[] args) {

        // 1、声明资源数量
        int carPosition = 3;

        // 2、根据资源数量创建 Semaphore 对象
        Semaphore semaphore = new Semaphore(carPosition);

        // 3、创建十个线程代表申请车位的十辆车
        for (int i = 0; i < 10; i++) {
            new Thread(()->{

                try {
                    // 申请资源
                    semaphore.acquire();

                    // 使用资源
                    System.out.println("【" + Thread.currentThread().getName() + "】号车辆【驶入】车位。");

                    TimeUnit.SECONDS.sleep(2);

                    System.out.println("【" + Thread.currentThread().getName() + "】号车辆【离开】车位。");

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    // 释放资源
                    semaphore.release();
                }

            }, "thread-" + i).start();
        }

    }

}
